import { ActionTree, ActionContext } from 'vuex'
import { RootState, useStore } from '@/store'
import { state, UserState } from './state'
import { Mutations } from './mutations'
import { UserMutationTypes } from './mutation-types'
import { UserActionTypes } from './action-types'
import { removeToken, setToken } from '@/utils/cookies'
// import { PermissionActionType } from '../permission/action-types'
import router, { resetRouter } from '@/router'
import { RouteRecordRaw } from 'vue-router'

import authApis from '@/apis/auth'
import resourceApis from '@/apis/resource'
import { md5 } from '@/utils/tools'
type AugmentedActionContext = {
  commit<K extends keyof Mutations>(
    key: K,
    payload: Parameters<Mutations[K]>[1],
  ): ReturnType<Mutations[K]>
} & Omit<ActionContext<UserState, RootState>, 'commit'>

export interface Actions {
  [UserActionTypes.ACTION_LOGIN](
    { commit }: AugmentedActionContext,
    userInfo: { username: string, password: string }
  ): void
  [UserActionTypes.ACTION_RESET_TOKEN](
    { commit }: AugmentedActionContext
  ): void
  [UserActionTypes.ACTION_GET_USER_INFO](
    { commit }: AugmentedActionContext
  ): void
  [UserActionTypes.ACTION_CHANGE_ROLES](
    { commit }: AugmentedActionContext, role: string
  ): void
  [UserActionTypes.ACTION_LOGIN_OUT](
    { commit }: AugmentedActionContext,
  ): void
  [UserActionTypes.ACTION_OSS_TOKEN]({ commit }: AugmentedActionContext): any
}

export const actions: ActionTree<UserState, RootState> & Actions = {
  async [UserActionTypes.ACTION_LOGIN](
    { commit }: AugmentedActionContext,
    userInfo: { username: string, password: string, type: number }
  ) {
    try {
      let { username, password, type } = userInfo;
      username = username.trim();
      password = md5(password);
      const res: any = await authApis.getToken({ username, password, type });
      console.log('登录结果', res)
      if (res.code === 0) {
        if (res.data.check) return { code: 2 }; // 需要邮箱验证
        // 存储token
        commit(UserMutationTypes.SET_TOKEN, res.data.token)
        return { code: 0 }
      }
    } catch (err) {
      console.log(err)
    }
  },

  [UserActionTypes.ACTION_RESET_TOKEN](
    { commit }: AugmentedActionContext) {
    removeToken()
    commit(UserMutationTypes.SET_TOKEN, '')
    commit(UserMutationTypes.SET_ROLES, [])
  },

  async [UserActionTypes.ACTION_GET_USER_INFO](
    { commit }: AugmentedActionContext,
  ) {
    if (state.token === '') {
      throw Error('token is undefined!')
    }
    const res: any = await authApis.getUserInfo();
    console.log('获取用户信息', res);
    if (res.code === 0) {
      commit(UserMutationTypes.SET_ROLES, res.data.roles)
      commit(UserMutationTypes.SET_USER, res.data.user)
      commit(UserMutationTypes.SET_PERMISSIONS, res.data.permissions);
      commit(UserMutationTypes.SET_COMPANY, res.data.company)
      const menus = [
        {
          component: "Basic",
          icon: "AppstoreOutlined",
          id: 1,
          meta: { title: "首页" },
          name: "Dashboard",
          parentId: 0,
          path: "/dashboard",
          perm: "dashboard",
          sort: 1,
          title: "首页",
          type: 0
        },
        ...res.data.menus
      ]
      commit(UserMutationTypes.SET_MENUS, menus)

    } else {
      commit(UserMutationTypes.SET_TOKEN, '')
      sessionStorage.clear();
    }
    return res;
  },

  async [UserActionTypes.ACTION_CHANGE_ROLES](
    { commit }: AugmentedActionContext,
    role: string
  ) {
    const token = role + '-token'
    const store = useStore()
    commit(UserMutationTypes.SET_TOKEN, token)
    setToken(token)
  },

  [UserActionTypes.ACTION_LOGIN_OUT](
    { commit }: AugmentedActionContext
  ) {
    removeToken()
    commit(UserMutationTypes.SET_TOKEN, '')
    // commit(UserMutationTypes.SET_ROLES, [])
    commit(UserMutationTypes.SET_ROLES, [])
    commit(UserMutationTypes.SET_USER, null)
    commit(UserMutationTypes.SET_PERMISSIONS, []);
    commit(UserMutationTypes.SET_COMPANY, null)
    resetRouter()
  },

  async [UserActionTypes.ACTION_OSS_TOKEN]({ commit }: AugmentedActionContext) {
    //#region 判断oss是否过期
    let isExpiration = false; // token是否过期 true:过期 false 未过期
    if (!state.ossConfig.stsToken || !state.ossConfig.expiration) {
      isExpiration = true;
    } else {
      const newDate = new Date().getTime(); // 当前时间戳
      const exDate = new Date(state.ossConfig.expiration).getTime(); // 过期时间
      if (exDate - newDate < 60 * 1000) {
        // 当前时间距离过期时间小于1分钟，判断过期
        isExpiration = true;
      } else {
        isExpiration = false;
      }
    }
    //#endregion

    if (!isExpiration) {
      return true;
    } else {
      // token过期，重新获取
      const res: any = await resourceApis.getOssToken();
      if (res.code === 0) {
        // 请求
        commit(UserMutationTypes.SET_OSSCONFIG, res.data);
        return true;
      } else {
        commit(UserMutationTypes.SET_OSSCONFIG, {});
        return false
      }
    }

  },


}
